<?php
/**
 * Date: 2021/8/4
 * Time: 17:26
 * 登录验证生成token
 */
namespace App\Service;
use Firebase\JWT\JWT;
use App\Model\UserModel;
use Symfony\Component\HttpFoundation\Response;



class Verify
{


    /*
     * 登录
     */
    public static function login(string $account, string $password):array
    {


        $user=UserModel::where('account',$account)->find(1);
        if(!$user){
            return ["code"=>Response::HTTP_FAIL,"msg"=>"账号不存在"];
        }else{

            $key=config('secret.key');
            if($user->password == md5($password.$key)){

                $payload=[
                    "user_id"=>$user->id,
                    "account"=>$user->account,
                    "exp" =>time()+7200
                ];

              $token=static::vaildation($payload);

               return ["code"=>Response::HTTP_OK,"msg"=>"登录成功","data"=>["token"=>$token]];
            }else{
                return ["code"=>Response::HTTP_FAIL,"msg"=>"密码错误"];
            }

        }


    }


    /*
     * token生成
     */
    public static function vaildation(array $data = [])
    {

        $key=config('secret.token_ket');
//        $payload = array(
//            "iss" => "http://example.org",
//            "aud" => "http://example.com",
//            "iat" => 1356999524,
//            "nbf" => 1357000000,
//            "exp" => 1628067276
//        );
        $payload=$data;

        /**
         * IMPORTANT:
         * You must specify supported algorithms for your application. See
         * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
         * for a list of spec-compliant algorithms.
         */
        $jwt = JWT::encode($payload, $key);
        //$decoded = JWT::decode($jwt, $key, array('HS256'));

        return $jwt;

        /*
         NOTE: This will now be an object instead of an associative array. To get
         an associative array, you will need to cast it as such:
        */

        $decoded_array = (array)$decoded;

        /**
         * You can add a leeway to account for when there is a clock skew times between
         * the signing and verifying servers. It is recommended that this leeway should
         * not be bigger than a few minutes.
         *
         * Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef
         */
        JWT::$leeway = 60; // $leeway in seconds
        $decoded = JWT::decode($jwt, $key, array('HS256'));

    }

    /*
     * token验证
     */
    public static function tokenVerify($token){

        $key=config('secret.token_ket');

        $decoded = JWT::decode($token, $key, array('HS256'));

        return $decoded;
    }
}